<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="java.util.Enumeration"%>
<%@page import="websql.Query"%>
<%@page import="unit.EscapeUnescape"%>
<%@page import="websql.Var"%><%@ page import="java.sql.*"%>
<%@page import="websql.Conn"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
	request.setCharacterEncoding("UTF-8");
%>
<%
	String sqid = request.getParameter("qid");
	if (!sqid.equals("")) {
		int qid = Integer.parseInt(sqid);
		String sql = Query.get("qsql", qid);

		Enumeration e = request.getParameterNames();
		while (e.hasMoreElements()) {
			String pars = (String) e.nextElement();
			if (!pars.equals("qid")) {
				int vid = Integer.parseInt(pars.substring(3));
				String befor = Var.get("vtar", vid);
				String after = request.getParameter(pars);
				sql = sql.replaceAll(befor, after);
				sql.replace(" ","");
			}

		}
		int cid = Integer.parseInt(Query.get("cid", qid));
		String drv = Conn.get("drv", cid);
		String url = Conn.get("url", cid);
		String usr = Conn.get("usr", cid);
		String psd = Conn.get("psd", cid);
		try {
			Class.forName(drv).newInstance();
			Connection conn = DriverManager
					.getConnection(url, usr, psd);
			Statement stm = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
			ResultSet rs = stm.executeQuery(sql);
			ResultSetMetaData rsmd = rs.getMetaData();
			int col = rsmd.getColumnCount();
			rs.last();
			int row = rs.getRow();
			rs.beforeFirst();
			out.println("<table><tr>");
			for (int i = 1; i <= col; i++) {
				out.println("<td>");
				out.println(rsmd.getColumnName(i));
				out.println("</td>");
			}
			out.println("<tr>");

			for (int i = 0; i < row; i++) {
				rs.next();
				out.println("<tr>");
				for (int j = 1; j < col + 1; j++) {
					out.println("<td>");
					out.println(rs.getString(j));
					out.println("</td>");
				}
				out.println("</tr>");
			}
			out.println("</table>");
			conn.close();
		} catch (Exception ex) {
			out.println("<xmp>发生异常,请检查sql语句，如果sql语句正确，请和管理员联系");
			out.println("你输入的sql语句是：\n" + sql + "\n");
			out.println("异常信息:\n" + ex + "\n");
			out.println("堆栈信息:\n" + ex.getStackTrace() + "\n</xmp>");
		}
	}
%>
</body>
</html>